package com.study.service;

import com.study.common.jdbc.MyJdbcTemplate;
import com.study.common.jdbc.MyTransactionManager;
import com.study.common.jdbc.annotation.MyTransactional;
import com.study.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.UUID;

/**
 * @author: chenhs
 * @date: Created in 16:31 2019/11/19
 **/
@Service
public class UserService {


    @Autowired
    JdbcTemplate jdbcTemplate;

    @Transactional(rollbackFor = Exception.class)
    public void insertUser(User user) {
        //打印异常错误栈，跟踪源码
        //new Exception().printStackTrace();

        jdbcTemplate.execute("insert into tb_user values ('" + user.getUserId() + "', '" + user.getUserName() + "')");

        jdbcTemplate.execute("insert into tb_log values ('" + UUID.randomUUID() + "', '新增用户：" + user.getUserName() + "', now())");

      //  int i = 1/0;

    }


    @Autowired
    MyJdbcTemplate myJdbcTemplate;

    @Autowired
    MyTransactionManager myTransactionManager;

    public void deleteUser(String userId) throws SQLException {

        Connection connection = myTransactionManager.getConnection();
        connection.setAutoCommit(false);

        try {
            //前提：保证同一个连接（拿到connection）
            //1. 删除用户
            myJdbcTemplate.execute("delete from tb_user where user_id = '" + userId + "'");

            //2. 记录日志
            myJdbcTemplate.execute("insert into tb_log values ('" + UUID.randomUUID() + "', '删除用户：" + userId + "', now())");

            //3. 逻辑
            int i = 1 / 0;

            connection.commit();
            System.out.println("事务提交！");
        } catch (Exception e) {
            e.printStackTrace();
            connection.rollback();
            System.out.println("事务回滚！");
        } finally {
            //关闭statement  （关闭对象）
            //关闭connection （释放连接，返还到连接池）
        }
    }

    @MyTransactional
    public void deleteUser2(String userId) throws SQLException {

            myJdbcTemplate.execute("delete from tb_user where user_id = '" + userId + "'");

            //2. 记录日志
            myJdbcTemplate.execute("insert into tb_log values ('" + UUID.randomUUID() + "', '删除用户：" + userId + "', now())");

            //3. 逻辑
            //int i = 1 / 0;
    }

}
